package org.smartjava.core.juc.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicExample {
    static volatile int i = 0;
    static volatile int k = 0;
    static volatile AtomicInteger atomicI = new AtomicInteger(0);

    public static void main(String[] args) {
        new Thread(() -> System.out.println("addAndMinusAtomic():" + addAndMinusAtomic())).start();
        new Thread(() -> System.out.println("addAndMinus():" + addAndMinus())).start();
        new Thread(() -> System.out.println("addAndMinusSynchronized():" + addAndMinusSynchronized())).start();
    }

    static int addAndMinusAtomic() {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(() -> {
            for (int j = 0; j < 10000; j++) {
                atomicI.incrementAndGet();
            }
            countDownLatch.countDown();
        }, "Thread add").start();
        new Thread(() -> {
            for (int j = 0; j < 10000; j++) {
                atomicI.decrementAndGet();
            }
            countDownLatch.countDown();
        }, "Thread minus").start();
        await(countDownLatch);
        return atomicI.get();
    }


    static int addAndMinus() {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(() -> {
            for (int j = 0; j < 100000; j++) {
                i++;
            }
            countDownLatch.countDown();
        }, "Thread add").start();
        new Thread(() -> {
            for (int j = 0; j < 100000; j++) {
                i--;
            }
            countDownLatch.countDown();
        }, "Thread minus").start();
        await(countDownLatch);
        return i;
    }

    static int addAndMinusSynchronized() {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(() -> {
            for (int j = 0; j < 100000; j++) {
                synchronized (AtomicExample.class) {
                    k++;
                }
            }
            countDownLatch.countDown();
        }, "Thread add").start();
        new Thread(() -> {
            for (int j = 0; j < 100000; j++) {
                synchronized (AtomicExample.class) {
                    k--;
                }
            }
            countDownLatch.countDown();
        }, "Thread minus").start();
        await(countDownLatch);
        return k;
    }

    static void await(CountDownLatch countDownLatch) {
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
